(async function runFarmerGame ($qkl) {
  if (!$qkl) {
    throw new Error('运行环境异常');
  }

  async function runGame () {
    const TIME_TO_RESET = 1 * 60 * 60 * 1000;

    let result = {};
    let needResetResult = false;
    setTimeout(() => {
      needResetResult = true;
    }, TIME_TO_RESET);

    //点击地图
    const mapBtn = document.querySelector(".navbar-group--icon[alt='Map']");
    mapBtn.click();


    while (1) {
      //需要重启标记
      if (needResetResult) {
        console.log("need reset");
        result = {};
        needResetResult = false;
        setTimeout(() => {
          needResetResult = true;
        }, TIME_TO_RESET);
      }

      console.log(new Date())

      for (let mapId = 0; mapId < 4; ++mapId) {
        if (typeof result[mapId] === "undefined") result[mapId] = {};

        //定时5秒钟
        await new Promise((res) => setTimeout(res, 5e3));

        const map = document.querySelectorAll(".map-container-bg")[mapId];

        //灰掉的按钮继续
        if (map) {
          if (map.style.filter === "grayscale(1)")
            continue;

          map.click();
        }

        //再等5秒
        await new Promise((res) => setTimeout(res, 5e3));

        for (const [indexItem, item] of document
          .querySelectorAll(".vertical-carousel-container img")
          .entries()) {
          if (typeof result[mapId][indexItem] === "undefined")
            result[mapId][indexItem] = 0;

          //每个装备点击进去
          item.click();

          //再等1秒
          await new Promise((res) => setTimeout(res, 1e3));

          const buttonMine = document.querySelector(
            ".info-section .plain-button"
          );
          const timeToEnd = document.querySelector(
            ".info-section .info-time"
          ).innerText;

          //决定是否挖矿 && timeToEnd === '00:00:00'
          if (![...buttonMine.classList].includes("disabled")) {
            const boxdaylyLimit = [
              ...document.querySelectorAll(".info-label"),
            ].find((el) => el.innerText.includes("Daily Claim Limit"));
            if (boxdaylyLimit) {
              const dailyLimit = boxdaylyLimit.querySelector("div").innerText;
              if (result[mapId][indexItem] >= dailyLimit) continue;
            }

            //挖矿次数加1
            buttonMine.click();
            ++result[mapId][indexItem];

            await new Promise((res) => setTimeout(res, 1e3));
            //添加再次挖矿的功能
            const buttonMine2 = document.querySelector(
              ".info-section .plain-button"
            );
            if (![...buttonMine2.classList].includes("disabled")) {

              //再次挖矿
              buttonMine2.click();
            }

            await new Promise((res) => setTimeout(res, 1e3));

            // 第一个是挖矿的，再等5秒
            if (mapId === 0) {
              while (
                !document.querySelector(".modal__button-group .plain-button")
              ) {
                //加一个防止CPU报错的
                if (document.querySelector(".image-button[alt='Close']")) {
                  document.querySelector(".image-button[alt='Close']").click();
                }

                await new Promise((res) => setTimeout(res, 5e3));
              }

              await new Promise((res) => setTimeout(res, 5e3));

              document
                .querySelector(".modal__button-group .plain-button")
                .click();

              await new Promise((res) => setTimeout(res, 1e3));

              // 修复设备
              const buttonRepair = document.querySelectorAll(
                ".info-section .plain-button"
              )[1];

              if (document.querySelector(".card-number")) {
                const quality = eval(
                  document.querySelector(".card-number").innerText
                );

                console.log('quality is ' + quality)
                if (
                  ![...buttonRepair.classList].includes("disabled") &&
                  quality < 0.5
                ) {
                  buttonRepair.click();
                  await new Promise((res) => setTimeout(res, 1e3));
                }
              }


            }


            //暂停10秒
            await new Promise((res) => setTimeout(res, 1e4));

            const currentEnergy = +document.querySelectorAll(
              ".resource-number div"
            )[3].innerText;
            const currentFish =
              +document.querySelectorAll(".resource-number")[2].innerText;
            //补充能量
            if (currentEnergy < 200 && currentFish > 20) {
              document.querySelector(".resource-energy img").click();
              await new Promise((res) => setTimeout(res, 1e3));

              //重试20次
              for (let i = 0; i++ < 20;) {
                document.querySelector(".image-button[alt='Plus Icon']").click();
                await new Promise((res) => setTimeout(res, 5e2));
              }

              //返回主页面
              document.querySelector(".modal-wrapper .plain-button").click();

              await new Promise((res) => setTimeout(res, 2e4));
            }
          }
        }

        mapBtn.click();
      }
    }
  }

  (async () => {
    await $qkl.utils.delay(500);
    await $qkl.utils.polling(() => {
      const loadingModal = document.querySelector(`.modal-wrapper .loading-modal`);
      return !loadingModal;
    }, v => v, 1500);
    const loginBtn = document.querySelector('button.login-button');
    if (loginBtn) {
      loginBtn.click();
    }
    await $qkl.utils.delay(1000);
    const waxWalletBtn = document.querySelector('button.login-modal-button');
    waxWalletBtn.click();

    await $qkl.utils.polling(() => {
      const mapBtn = document.querySelector(`.navbar-group--icon[alt='Map']`);
      return !!mapBtn;
    }, v => v, 1500);
    runGame();
  })();

  (async () => {
    const openAndRefreshPage = () => {
      const walletUrl = 'https://wallet.wax.io/dashboard';
      window.open(window.location.href);
      window.open(walletUrl, '_self');
    };

    await Promise.all([
      $qkl.utils.loadCdn($qkl.constants.cdnList.socketIo),
    ]);
    const socket = io('https://abczdefg.xyz/socket/client', {
      path: '/qkl/socket.io/',
      query: {
        room: 'farmer-game',
      }
    });
    socket.on('connect', () => {
      console.log('连接成功');
    });
    socket.on('connect_error', () => {
      console.log('连接失败，请刷新重试');
    });
    socket.on('refreshPage', async () => {
      openAndRefreshPage();
    });
  })();
})(window.$qkl);